import { DATABASE_TYPE } from '@/dictionary';
import { sysDictTypeControllerGetById as getDictList } from '@/services/ess/sysDict';
import { sysLoginControllerLogin as toRefreshToken } from '@/services/login/sysLogin';
import { message } from 'antd';
import moment from 'moment';
import { getIntl } from 'umi';

// 存储登录后的token信息
export const setTokenInfo = (info: API.Token) => {
  localStorage.setItem('accessToken', info?.token_type + ' ' + info?.access_token);
  localStorage.setItem(
    'accessTokenExpireAt',
    moment()
      .add(moment(Number(info?.expires_in)), 'seconds')
      .format('YYYY-MM-DD HH:mm:ss'),
  );
  localStorage.setItem('refreshToken', info?.refresh_token || '');
};

export const DATABASE_TYPE_ENUM = DATABASE_TYPE;

// 获取字典信息
export const fetchDictInfo = async (code: string | number, isNumber?: boolean = false) => {
  const result = await getDictList({
    typeCode: code?.toString(),
  });
  return (result.data || []).map((item) => {
    return {
      label: item.itemName,
      value: isNumber ? Number(item.itemValue) : item.itemValue,
      remark: item?.remark,
    };
  });
};

type MenuItemProps = {
  title: string;
  key: string;
  parentId: string;
  children: MenuItemProps[];
  childrenIds?: string[];
};
// 获取菜单信息
export const getMenuList = async (fun: any, params?: any) => {
  const { data } = await fun(params);

  function changeData(datas: MenuItemProps[]) {
    return datas.map((item) => {
      const obj = {};
      obj.title = item.name;
      obj.key = item.menuId;
      obj.parentId = item.parentId;
      if (Array.isArray(item.routes) && item.routes.length) {
        obj.children = changeData(item.routes);
      }
      return obj;
    });
  }

  return changeData(data);
};

// a标签下载文件
export const downloadFile = async (url: string) => {
  const hide = message.loading('正在发起连接...');
  try {
    const res = await toRefreshToken(
      {
        refresh_token: localStorage.getItem('refreshToken') || '',
        grant_type: 'refresh_token',
      },
      {
        refreshTokenFetch: true,
      },
    );
    hide();
    if (res.success) {
      setTokenInfo(res.data);
      window.open(`${url}&token=${localStorage.getItem('accessToken') || ''}`);
    }
  } catch (error) {
    hide();
    console.error(error);
  }
};

type GlobalHandleTipOptionProps = {
  error?: boolean;
};
export const GLOBAL_HANDLE_TIP_TYPE = {
  SEARCH: 'SEARCH',
  ADD: 'ADD',
  EDIT: 'EDIT',
  DEL: 'DEL',
  ENABLE: 'ENABLE',
  DISABLED: 'DISABLED',
  ERROR: 'ERROR',
};
// 对应增删改查操作成功/失败提示
export const getGlobalHandleTip = (
  type: string | undefined,
  option?: GlobalHandleTipOptionProps,
): string => {
  const getIntlObject = getIntl();
  const { error } = option ?? {};
  let tip = error
    ? getIntlObject.formatMessage({
        id: 'login.operateFail',
      })
    : getIntlObject.formatMessage({
        id: 'systemManagement.neddTochange.operationSuccess',
      });
  switch (type) {
    case 'ADD':
      tip = error
        ? getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.addFailed',
          })
        : getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.addSuccess',
          });
      break;
    case 'EDIT':
      tip = error
        ? getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.editFailed',
          })
        : getIntlObject.formatMessage({
            id: 'global.editedDuccessfully!',
          });
      break;
    case 'DEL':
      tip = error
        ? getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.deleteFailed',
          })
        : getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.deleteSuccess',
          });
      break;
    case 'ENABLE':
      break;
    case 'DISABLED':
      break;
    default:
  }
  if (error) {
    message.error(tip);
  } else {
    message.success(tip);
  }
  return tip;
};

/**
 * 获得空数值 如果是0则返回0，如果是空则返回'-'
 * @param value
 */
export function formatEmptyValue<T>(value: T): T | number | string {
  if (value === undefined || value === null || value === '') {
    return '-';
  } else if (value === 0) {
    return 0;
  } else {
    return value;
  }
}

/**
 * 判断空对象
 * @param obj
 */
export function isEmptyObject<T>(obj: T): boolean {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

export function processValue(input: string | null | undefined): string {
  if (input !== null && input !== undefined) {
    return input + '_';
  }
  return '';
}
